package controllers

import (
	customv1 "K3d/api/v1"
	v12 "k8s.io/api/batch/v1"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"strconv"
)

func (r *K3dReconciler) getDeleteJob(instance *customv1.K3d) (customv1.OwnJob, error) {
	labelMap := make(map[string]string, 1)
	labelMap["app"] = "k3d-" + instance.Spec.Job.ClusterName

	// env参数格式化
	defaultMode := int32(0555)
	kafkaUrl := instance.Spec.Job.KafkaUrl
	if kafkaUrl == "" {
		kafkaUrl = "10.252.248.29:31000"
	}

	// image初始化
	imageName := instance.Spec.Job.Image
	if imageName == "" {
		imageName = "artifactory.dep.devops.cmit.cloud:20101/tools/sshpass:v2"
	}

	//nodeSelector
	//nodeSelector := instance.Spec.Job.NodeSelector
	//if nodeSelector == nil {
	//	nodeSelector = make(map[string]string)
	//	nodeSelector["kube-edge-role"] = "cluster-manager-quay1"
	//}

	ownJob := customv1.OwnJob{
		Spec: v12.JobSpec{
			Template: v1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labelMap,
				},
				Spec: v1.PodSpec{
					NodeSelector: map[string]string{
						"group-k3d": "k3d",
					},
					RestartPolicy: v1.RestartPolicyNever,
					Containers: []v1.Container{
						{
							Image:           imageName,
							ImagePullPolicy: v1.PullIfNotPresent,
							Name:            "delete-k3dcluster",
							Command:         []string{"/bin/sh", "-c"},
							Args:            []string{"/home/k3d/k3d-delete.sh"},
							VolumeMounts: []v1.VolumeMount{
								{
									Name:      "k3d-delete-sh",
									MountPath: "/home/k3d/k3d-delete.sh",
									SubPath:   "k3d-delete.sh",
								},
								{
									Name:      "server-pass",
									MountPath: "/home/k3d/server-pass",
									SubPath:   "server-pass",
								},
								{
									Name:      "shared-logs",
									MountPath: "/home/k3d/logs",
								},
							},
							Env: []v1.EnvVar{
								{
									Name:  "IP",
									Value: instance.Spec.Job.HostIp,
								},
								{
									Name:  "CLUSTERNAME",
									Value: instance.Spec.Job.ClusterName,
								},
								{
									Name:  "K3D_HOST",
									Value: instance.Spec.Job.ClusterHost,
								},
								{
									Name:  "KAFKAURL",
									Value: kafkaUrl,
								},
							},
						},
					},
					Volumes: []v1.Volume{
						{
							Name: "k3d-delete-sh",
							VolumeSource: v1.VolumeSource{
								ConfigMap: &v1.ConfigMapVolumeSource{
									LocalObjectReference: v1.LocalObjectReference{
										Name: "k3d-delete",
									},
									DefaultMode: &defaultMode,
									Items: []v1.KeyToPath{
										{
											Key:  "k3d-delete.sh",
											Path: "k3d-delete.sh",
										},
									},
								},
							},
						},
						{
							Name: "server-pass",
							VolumeSource: v1.VolumeSource{
								Secret: &v1.SecretVolumeSource{
									SecretName: "server-pass",
									Items: []v1.KeyToPath{
										{
											Key:  "server-pass",
											Path: "server-pass",
										},
									},
								},
							},
						},
						{
							Name: "shared-logs",
							VolumeSource: v1.VolumeSource{
								EmptyDir: &v1.EmptyDirVolumeSource{},
							},
						},
					},
				},
			},
		},
	}

	return ownJob, nil
}

func (r *K3dReconciler) getCreateJob(instance *customv1.K3d) (customv1.OwnJob, error) {
	labelMap := make(map[string]string, 1)
	labelMap["app"] = "k3d-" + instance.Spec.Job.ClusterName

	// env参数格式化
	defaultMode := int32(0555)
	clusterPort := strconv.Itoa(*instance.Spec.Job.ClusterPort)
	exposePort := strconv.Itoa(*instance.Spec.Job.ExposePort)
	server := strconv.Itoa(*instance.Spec.Job.Server)
	agent := strconv.Itoa(*instance.Spec.Job.Agent)
	clusterName := "k3d-" + instance.Spec.Job.ClusterName
	kafkaUrl := instance.Spec.Job.KafkaUrl
	if kafkaUrl == "" {
		//kafkaUrl = "10.252.248.29:31000"
		kafkaUrl = "devops-msgmanage.cmccdevops-test-pod6:9090" //pod6
	}

	// image初始化
	initImageName := instance.Spec.Job.InitImage
	imageName := instance.Spec.Job.Image
	if initImageName == "" {
		initImageName = "artifactory.dep.devops.cmit.cloud:20101/tools/sshpass:v1"
	}
	if imageName == "" {
		imageName = "artifactory.dep.devops.cmit.cloud:20101/tools/manager-k3dcluster:v202108050001"
	}

	ownJob := customv1.OwnJob{
		Spec: v12.JobSpec{
			Template: v1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: labelMap,
				},
				Spec: v1.PodSpec{
					NodeSelector: map[string]string{
						"group-k3d": "k3d",
					},
					RestartPolicy: v1.RestartPolicyNever,
					InitContainers: []v1.Container{
						{
							Image:           initImageName,
							ImagePullPolicy: v1.PullIfNotPresent,
							Name:            "sshpass",
							Command:         []string{"/home/k3d/k3d-create.sh"},
							VolumeMounts: []v1.VolumeMount{
								{
									Name:      "k3d-create-sh",
									MountPath: "/home/k3d/k3d-create.sh",
									SubPath:   "k3d-create.sh",
								},
								{
									Name:      "k3d-config-yaml",
									MountPath: "/home/k3d/k3d-config.yaml",
									SubPath:   "k3d-config.yaml",
								},
								{
									Name:      "k3d-console-yaml",
									MountPath: "/home/k3d/k3d-console.yaml",
									SubPath:   "k3d-console.yaml",
								},
								{
									Name:      "server-pass",
									MountPath: "/home/k3d/server-pass",
									SubPath:   "server-pass",
								},
								{
									Name:      "k3d-kubeconfig",
									MountPath: "/home/k3d/cluster",
								},
								{
									Name:      "shared-logs",
									MountPath: "/home/k3d/logs",
								},
								{
									Name:      "istio-config",
									MountPath: "/home/k3d/istio-k3d.yaml",
								},
							},
						},
					},
					Containers: []v1.Container{
						{
							Image:           imageName,
							ImagePullPolicy: v1.PullIfNotPresent,
							Name:            "manager-k3dcluster",
							Command:         []string{"/bin/sh", "-c"},
							Args:            []string{"/app"},
							VolumeMounts: []v1.VolumeMount{
								{
									Name:      "k3d-kubeconfig",
									MountPath: "/home/k3d/cluster",
								},
								{
									Name:      "shared-logs",
									MountPath: "/home/k3d/logs",
								},
							},
							Env: []v1.EnvVar{
								{
									Name:  "CLUSTERNAME",
									Value: clusterName,
								},
								//{
								//	Name:  "CLUSTERDNS",
								//	Value: clusterdDns,
								//},
								{
									Name:  "CONFIGNAME",
									Value: "config",
								},
								{
									Name:  "CONFIGPATH",
									Value: "home/k3d/cluster",
								},
								{
									Name:  "KAFKAURL",
									Value: kafkaUrl,
								},
								{
									Name:  "LOGDIR",
									Value: "/home/k3d/logs/create.log",
								},
								{
									Name:  "CLUSTERTYPE",
									Value: "k3d",
								},
							},
						},
					},
					Volumes: []v1.Volume{
						{
							Name: "k3d-create-sh",
							VolumeSource: v1.VolumeSource{
								ConfigMap: &v1.ConfigMapVolumeSource{
									LocalObjectReference: v1.LocalObjectReference{
										Name: "k3d-create",
									},
									DefaultMode: &defaultMode,
									Items: []v1.KeyToPath{
										{
											Key:  "k3d-create.sh",
											Path: "k3d-create.sh",
										},
									},
								},
							},
						},
						{
							Name: "k3d-config-yaml",
							VolumeSource: v1.VolumeSource{
								ConfigMap: &v1.ConfigMapVolumeSource{
									LocalObjectReference: v1.LocalObjectReference{
										Name: "k3d-config",
									},
								},
							},
						},
						{
							Name: "k3d-console-yaml",
							VolumeSource: v1.VolumeSource{
								ConfigMap: &v1.ConfigMapVolumeSource{
									LocalObjectReference: v1.LocalObjectReference{
										Name: "k3d-console",
									},
								},
							},
						},
						{
							Name: "server-pass",
							VolumeSource: v1.VolumeSource{
								Secret: &v1.SecretVolumeSource{
									SecretName: "server-pass",
									Items: []v1.KeyToPath{
										{
											Key:  "server-pass",
											Path: "server-pass",
										},
									},
								},
							},
						},
						{
							Name: "k3d-kubeconfig",
							VolumeSource: v1.VolumeSource{
								EmptyDir: &v1.EmptyDirVolumeSource{},
							},
						},
						{
							Name: "shared-logs",
							VolumeSource: v1.VolumeSource{
								EmptyDir: &v1.EmptyDirVolumeSource{},
							},
						},
						{
							Name: "istio-config",
							VolumeSource: v1.VolumeSource{
								HostPath: &v1.HostPathVolumeSource{
									Path: "/home/k3d/istio-k3d.yaml",
								},
							},
						},
					},
				},
			},
		},
	}

	//add some customize envs, ignore this step if you don't need it
	customizeEnvs := []v1.EnvVar{
		{
			Name:  "IP",
			Value: instance.Spec.Job.HostIp,
		},
		{
			Name:  "CLUSTERNAME",
			Value: instance.Spec.Job.ClusterName,
		},
		{
			Name:  "K3D_HOST",
			Value: instance.Spec.Job.ClusterHost,
		},
		{
			Name:  "K3D_HOSTPORT",
			Value: clusterPort,
		},
		{
			Name:  "K3D_EXPOSEPORT",
			Value: exposePort,
		},
		{
			Name:  "SERVERS",
			Value: server,
		},
		{
			Name:  "AGENTS",
			Value: agent,
		},
	}

	var specEnvs []v1.EnvVar
	templateEnvs := ownJob.Spec.Template.Spec.InitContainers[0].Env
	for index := range templateEnvs {
		if templateEnvs[index].Name != "CLUSTERNAME" && templateEnvs[index].Name != "HOSTIP" && templateEnvs[index].Name != "SERVER" && templateEnvs[index].Name != "AGENT" {
			specEnvs = append(specEnvs, templateEnvs[index])
		}
	}
	ownJob.Spec.Template.Spec.InitContainers[0].Env = append(specEnvs, customizeEnvs...)

	return ownJob, nil
}
